package manage.actions;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import manage.commons.Constants;
import manage.commons.annontations.RequiredLogin;
import manage.commons.annontations.RequiredLogin.Required;
import manage.commons.utils.CookieUtils;
import manage.commons.utils.RandomCode;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 验证码处理
 * 
 * @author dongji
 * @since 2012-11-9 下午05:55:39
 */
@RequiredLogin(Required.FALSE)
public class CaptchaAction extends ActionSupport implements
		ServletRequestAware, ServletResponseAware, Serializable {

	private static final long serialVersionUID = 1L;
	private HttpServletResponse response;
	private HttpServletRequest request;

	/**
	 * 获取验证码
	 */
	@Override
	@Action("captcha")
	public String execute() throws Exception {
		RandomCode image = new RandomCode();
		// 禁止图像缓存。
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		// 将图像输出到输出流中。
		ServletOutputStream sos = response.getOutputStream();
		CookieUtils.addCookie(response, Constants.COOKIE_CAPTCHA_KEY,
				image.getEncryptValue());
		ImageIO.write(image.getBuffImg(), "jpeg", sos);
		IOUtils.closeQuietly(sos);
		return NONE;
	}

	/**
	 * 返回用户输入验证码加密后的结果
	 * 
	 * @return
	 * @throws IOException
	 */
	@Action("get-captcha-answer")
	public String generate() throws IOException {
		response.setContentType("text/html; charset=utf-8");
		response.setCharacterEncoding("utf-8");
		String randomCode = request.getParameter(Constants.COOKIE_CAPTCHA_KEY);
		if (StringUtils.isBlank(randomCode)) {
			randomCode = "errorRandomCode";
		}
		PrintWriter out = response.getWriter();
		out.write(RandomCode.getEncryptValue(randomCode));
		out.flush();
		IOUtils.closeQuietly(out);
		return NONE;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

}
